package com.base_data_handler.function.air;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.alibaba.fastjson.JSONArray;
import com.base_data_handler.function.model.AirInfo;
import com.base_data_handler.utils.DataSourceUtils;
import com.base_data_handler.utils.NetData;
import com.base_data_handler.utils.PinyinUtil;
import com.base_data_handler.utils.StringUtils;

public class AirCntyInCityHandler {
//	private	static QueryRunner qr=new QueryRunner(DruidPlugin.getDataSource());
	private	static QueryRunner qr=new QueryRunner(DataSourceUtils.getDatasSource());
	/**
	 * 转换成json代码
	 * @param json
	 * @return
	 */
	private static final Logger log = Logger.getLogger(AirCntyInCityHandler.class.getName());
 	private static  List<AirInfo> readjson(String json) {
 		List<AirInfo> arr=null;
 		try {
 			if(json.contains("error"))return arr;
 			arr = JSONArray.parseArray(json, AirInfo.class);
 		
		} catch (Exception e) {
			// TODO: handle exception
			log.info("数据解析错误"+e.getMessage());
		}
	
		return arr;
	}
	
 	
 
 
    /**
     * 获取每个市所有检测点数据数据
     * city="baoji"
     */
	public static void saveCntyInCity2db(String city){
  		 int rs = 0;
  		 StringBuilder sb=new StringBuilder();
  		  sb.append(" insert into d_airqulity_cnty ")
  		    .append(" (aqi,area,co,co_24h,no2,no2_24h,o3,o3_24h,o3_8h,o3_8h_24h,")
	  		.append(" pm10,pm10_24h,pm2_5,pm2_5_24h,level,quality,so2,so2_24h,")
	  		.append(" primary_pollutant,time_point,station_code,position_name,id) ")
	  		.append(" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ")
	  		.append(" ON DUPLICATE KEY UPDATE   ")
	   		.append(" aqi=?");//如果主键相同更新数据
  	List<AirInfo> arr = readjson(NetData.getStringData("http://www.pm25.in/api/querys/aqi_details.json?city="+city+"&token=x7KbGxeVnqmwXwV8zXAB&stations=yes"));
//  	获取一个城市所有监测点数据 如果=no只返回本市
//  	http://www.pm25.in/api/querys/aqi_details.json?city=baoji&token=x7KbGxeVnqmwXwV8zXAB&stations=yes
  		if(arr==null){
  			log.info("没有获取到数据……");
  			return;
  		}else{
  			log.info(arr.toString());
  		}
  		AirInfo ai=null;
  		try {
				Object[][] params=new Object[arr.size()][24];
				for (int i= 0; i < arr.size(); i++) {
					ai=arr.get(i);
					params[i][0]=ai.getAqi();
					params[i][1]=ai.getArea();
					params[i][2]=ai.getCo();
					params[i][3]=ai.getCo_24h();
					params[i][4]=ai.getNo2();
					params[i][5]=ai.getNo2_24h();
					params[i][6]=ai.getO3();
					params[i][7]=ai.getO3_24h();
					params[i][8]=ai.getO3_8h();
					params[i][9]=ai.getO3_8h_24h();
					params[i][10]=ai.getPm10();
					params[i][11]=ai.getPm10_24h();
					params[i][12]=ai.getPm2_5();
					params[i][13]=ai.getPm2_5_24h();
					params[i][14]=AirLevel.aqiLevel(ai.getAqi());
					params[i][15]=null==ai.getQuality()?AirLevel.aqiQuality(params[i][14].toString()):ai.getQuality();
					params[i][16]=ai.getSo2();
					params[i][17]=ai.getSo2_24h();
					params[i][18]=ai.getPrimary_pollutant();
					params[i][19]=ai.getTime_point();
					params[i][20]=ai.getStation_code();
					params[i][21]=ai.getPosition_name();
					if(StringUtils.isEmpty(ai.getPosition_name())){
						params[i][22]=ai.getTime_point();
					}else{
						params[i][22]=ai.getTime_point()+ai.getPosition_name();
					}
					
					params[i][23]=ai.getAqi();
				} 
				qr.batch(sb.toString(), params);
			} catch (SQLException e) {
				 e.printStackTrace();
			}
	}

	/**
	 * 
	 * @param sqlIn not in('陕西','甘肃')
	 * @return
	 */
	public static String[] getCityEn(String sqlInOrNot){
		List<Map<String, Object>> list=null;
		String sql="select b.city_name from b_weaher_china_city b where b.province_name "+sqlInOrNot+"  GROUP BY b.city_name";
		String [] arr=null;
		try {
			 list = qr.query(sql, new MapListHandler());
			 arr=new String [list.size()];
			 for (int i = 0; i < list.size(); i++) {
				 arr[i]=  PinyinUtil.toHanyuPinyin(list.get(i).get("city_name").toString());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;	
	}
	
		
 public static void main(String[] args) {
//	 xingping,hancheng
//	 String str="xian,baoji,tongchuan,xianyang,weinan,yanan,hanzhong,yulin,ankang,shangluo";
	 saveCntyInCity2db("xian");
//	 String[] citys = str.split(",");
//	 for (int i = 0; i < citys.length; i++) {
//		 saveCntyInCity2db(citys[i]);
//	}
	 
	 
	 String[] citys = getCityEn("not in('')");
	 if(null!=citys){
		 for (int i = 0; i < citys.length; i++) {
			 saveCntyInCity2db(citys[i]);
		}
	 }
	// saveCntyInCity2db("xianyang");
}
}
